package com.lbz.service.Impl;

import com.google.common.collect.Lists;
import com.lbz.service.FileService;
import com.lbz.utils.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 林必昭
 * @Date 2019/6/15 23:25
 */

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file, String path) {

        //1.获取原文件名
        String fileName = file.getOriginalFilename();
        //2.获取文件后缀
        String fileExtendsName = fileName.substring(fileName.lastIndexOf(".")+1);
        //3.目标文件名
        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtendsName;
        log.info("开始上传文件，上传原文件名：{},上传路径：{},新文件名：{}",fileName,path,uploadFileName);

        File fileDir = new File(path);
        if (!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }

        File targetFile = new File(path,uploadFileName);
        try {
            //SpringMVC封装的方法，用于图片上传
            file.transferTo(targetFile);

            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            //上传成功后，删除目标文件
            targetFile.delete();
        }catch (IOException e){
            log.error("文件上传异常");
        }
        //a.jpg
        return targetFile.getName();
    }
}
